package com.oocl.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.oocl.constant.ApplyStatus;
import com.oocl.pojo.Merchant;
import com.oocl.service.MerchantManager;
import com.oocl.service.factory.MerchantManagerFactory;

/**
 * Servlet implementation class ProcessServlet
 */
@WebServlet("/sec/process")
public class ProcessServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MerchantManager manager;
	private Logger logger = Logger.getLogger(ProcessServlet.class);
	
    public ProcessServlet() {
        super();
        manager = MerchantManagerFactory.getInstance();
    }
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info("submit to process merchant apply");
		String result = request.getParameter("result");
		String id = request.getParameter("id");
		if("1".equals(result)){
			manager.updateStatus(id, ApplyStatus.APPROVED);
		}else if("2".equals(result)){
			String bcontent = request.getParameter("bcontent");
			if(null==bcontent || "".equals(bcontent)){
				sendError("必须填写驳回理由", request, response,id,bcontent);
				return;
			}
			if(bcontent.length()>100){
				sendError("驳回理由必须在一百字以内", request, response,id,bcontent);
				return;
			}
			Merchant merchant = manager.findMerchantById(id);
			merchant.setbContent(bcontent);
			merchant.setStatus(ApplyStatus.REJECTED);
			manager.update(merchant);
		}
		response.sendRedirect("pendingList");
	}
	
	private void sendError(String errorMsg,HttpServletRequest request,HttpServletResponse response,String id,String content) throws ServletException, IOException{
		Merchant merchant = manager.findMerchantById(id);
		merchant.setbContent(content);
		merchant.setStatus(2);
		request.setAttribute("merchant", merchant);
		request.setAttribute("editError", errorMsg);
		request.getRequestDispatcher("../WEB-INF/views/process.jsp").forward(request, response);
	}

}
